package com.sl.crawler.common.exception;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogErrorUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogErrorUtil.class);

    /**
     * 记录日志，并抛出异常
     *
     * @param errorInfo
     * @throws AppException
     */
    public static void logErrorAndThrowEx(String errorInfo) throws AppException {
        LOGGER.error(errorInfo);
        throw new AppException(errorInfo);
    }

    /**
     * 记录日志，并抛出异常
     *
     * @param logger
     * @param errorInfo
     * @throws AppException
     */
    public static void logErrorAndThrowEx(Logger logger, String errorInfo) throws AppException {
        logger.error(errorInfo);
        throw new AppException(errorInfo);
    }

    /**
     * 记录日志，并抛出异常
     *
     * @param logger
     * @param loggerInfo
     * @param errorInfo
     * @throws AppException
     */
    public static void logErrorAndThrowEx(Logger logger, String loggerInfo, String errorInfo) throws AppException {
        logger.error(loggerInfo);
        throw new AppException(errorInfo);
    }

    /**
     * 记录日志，并抛出异常
     *
     * @param logger
     * @param errorInfo
     * @throws AppException
     */
    public static void logErrorAndThrowEx(Logger logger, AppException e, String errorInfo) throws AppException {
        logger.error(errorInfo, e);
        throw new AppException(errorInfo, e);
    }

    /**
     * 记录日志，并抛出异常
     *
     * @param logger
     * @param errorInfo
     * @throws AppException
     */
    public static void logErrorAndThrowEx(Logger logger, Exception e, String errorInfo) throws Exception {
        logger.error(errorInfo, e);
        throw new Exception(errorInfo, e);
    }

    /**
     * 如果操作数据库结果条数小于1，记录日志，并抛出异常
     *
     * @param log
     * @param resultCount
     * @param info
     */
    public static void logDBResultAndThrowEx(Logger log, int resultCount, String info) {
        // 默认最小执行成功条数为1
        logDBResultAndThrowEx(log, resultCount, 1, info);
    }

    /**
     * 当结果小于指定条数返回错误
     *
     * @param log
     * @param resultCount
     * @param minResultCount
     * @param info
     */
    public static void logDBResultAndThrowEx(Logger log, int resultCount, int minResultCount, String info) {
        if (resultCount < minResultCount) {
            logErrorAndThrowEx(log, info + ",返回数据库条数=" + resultCount);
        }
    }


    /**
     * 数据库影响行数不为1则记录日志并抛出异常
     * @param affectRows
     * @param info
     */
    public static void logAndThrowExDbNotOne(Integer affectRows, String info) {
        if (1 != affectRows) {
            info = StringUtils.isBlank(info) ? "" : info + ", ";
            String msg = info + "数据库影响行数不为1, 实际影响行数为" + affectRows;
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }
    }
}

